Ext.onReady(function(){
	MENU_DISK.initPage();
});
var MENU_DISK={
		initPage: function(){
			Ext.create('Ext.container.Viewport', {
			    layout: 'border',
			    frame:false,
			    border:false,
			    items: [{
			    	region: 'west',
			        split: true,
			        width: Utils.getWidth()*0.2,
			        layout: 'fit',
			        items:[MENU_DISK.initMenuTree()]
			    },{
			    	region:'center',
			    	layout: {
		                type: 'border'
		            },
		            items:[{
		            	region: 'north',
		            	height: Utils.getHeight()*0.6,
		                border: false,
		                layout: 'fit',
		                items:[MENU_DISK.menuRoleGrid()]
		            },{
		            	region: 'center',
		            	height: Utils.getHeight()*0.4,
		                border: false,
		                layout: 'fit',
		                items:[MENU_DISK.createMenuRoleBtnPersim()]
		            }]
			    }]
			});
		},
		initMenuTree: function(){
			//树
		 	var tree = Ext.create("Ext.com.bkfm.tree",{
		 		id: "menuTree",
		 		rootVisible: true,
		 		rootLabel: "系统菜单",
		 		treeConfigId: "menu",
		 		rootTreeId: "00000000000000000000000000000001",
		 		objPath: 'ROOT/XTGLPT/JCSJGL/CDXX/BLK_BASE_MENUS',
		 		border: false,
		 		autoScroll: true,
		 		mappingField:["IS_CHILD_MENU","MENU_ID"],
		 		tbar:[{
		 			text: '新增',
		 			iconCls: 'add',
		 			handler: function(){
		 				var selOrgNode = tree.getSelectNode();
		 				if(selOrgNode.get("is_child_menu") == Constants.NO){
		 					AjaxUtils.showError("所选择的菜单类型为“不包含下级子菜单”，无法在当前菜单下新增，如需新增下级菜单请先修改所选择菜单的属性");
		 					return;
		 				}
		 				MENU_DISK.editMenuTree();
		 			}
		 		},{
		 			text: '修改',
		 			iconCls: 'edit',
		 			handler: function(){
		 				var menuTree = Ext.getCmp("menuTree");
		 				MENU_DISK.editMenuTree(menuTree.getSelectNode());
		 			}
		 		},{
		 			text: '删除',
		 			iconCls: 'delete',
		 			handler: function(){
		 				var menuTree = Ext.getCmp("menuTree");
	 					menuTree.delSelectNode(menuTree.getSelectNode());
		 			}
		 		}],
		 		viewConfig:{
		            plugins :{
		                ptype:'treeviewdragdrop',
		                //appendOnly:true         //只能拖着带非叶节点上
		            },
		            listeners:{//监听器
		                drop:function(node,data,overModel,dropPosition,options){
		                    return false;
		                },
		                beforedrop:function(node,data,overModel,dropPosition,dropFunction,options){
		                	return false;
		                }
		            }
		        }
		 	});
		 	tree.on("itemclick",function(view,record,item,index,e,opts){
		 		var id = record.get("id");
		 		var title = record.get("text");
		 		var isleaf = record.get("leaf");
		 		var menuRoleGrid = Ext.getCmp("menuRoleGrid");
		 		menuRoleGrid.search(" MENU_RWID='"+id+"'");
		 		
		 		//查询菜单对应功能按钮
				if(record.raw.menu_type == '1'){
					Ext.getCmp("menuRoleBtnGrid").getSelectionModel().deselectAll();
					Ext.getCmp("menuRoleBtnGrid").search(" BTN_LEVEL IN ('0') OR MENU_RWID='"+id+"'");
				}else{
					Ext.getCmp("menuRoleBtnGrid").getStore().removeAll();
				}

		 	})
		 	return tree;
		},
		editMenuTree: function(record){
			var menuTree = Ext.getCmp("menuTree");
			var form = Ext.create('Ext.com.bkfm.form', {
				showGroup : false,
				columnCount: 2,
				border : false,
				frameborder : false,
				id: "menuform",
				objPath : "ROOT/XTGLPT/JCSJGL/CDXX/BLK_BASE_MENUS",
				listeners:{
					afterrender: function(form,eopts){
						if(record){
							//存在表示编辑
							form.loadRemoteData(record.get("id"));
						}else{
							var selMenuNode = menuTree.getSelectNode();
							form.setFieldValue(form.findById("PARENT_MENU_ID"),{
								VALUE: selMenuNode.get("id"),
								DISPLAYVALUE: selMenuNode.get("text")
							});
							//初始化菜单编码
							//根节点
							var SQL = "SELECT IFNULL(MAX(MENU_ID),'') AS MENU_ID FROM BLK_BASE_MENUS WHERE PARENT_MENU_ID='"+selMenuNode.getId()+"' ";
							BkfmDBUtils.Query(SQL,function(result){
								if(result.status == "OK"){
									if(result.list !=null && result.list.length >0){
										debugger;
										var old_menu_id = (result.list)[0]["MENU_ID"];
										if(!Ext.isEmpty(old_menu_id)){
											var new_menu_id = Utils.fillNumberZero(parseInt(old_menu_id)+1,old_menu_id.length);
											form.findById("MENU_ID").setValue(new_menu_id);
											return;
										}
									}
								}
								//
								new_menu_id = selMenuNode.get("menu_id")+"01";
								form.findById("MENU_ID").setValue(new_menu_id);
								
							});
						}
					}
				}
			});
			var win = Ext.create('Ext.com.bkfm.window', {
				title : '编辑菜单',
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.5,
				width : Utils.getWidth()*0.5,
				items: [form],
				tbar : [ {
					text : '保存',
					iconCls : 'save',
					handler : function() {
						if(form.getFormState() == Constants.RECORD_NEW){
							//新增判断菜单编码是否唯一
							var count = BkfmDBUtils.CheckNumber({
								objPath: "ROOT/XTGLPT/JCSJGL/CDXX/BLK_BASE_MENUS",
								filter: " MENU_ID ='"+form.findById("MENU_ID").getValue()+"'"
							});
							if(Ext.isEmpty(count) || count >0){
								AjaxUtils.showError("当前菜单编码已经存在");
								return;
							}
						}
						form.save(function(){
							menuTree.reloadSelectNode();
							win.close();
						});

					}
				} ]
			});
			win.show(this,function(){
				if(record){
					form.loadRemoteData(record.get("id"));
				}
				form.findById("ICON_URL").getEl().on("click",function(){
					//var me = this;
					MENU_DISK.createIconPanel();
				});
			});
		},
		menuRoleGrid: function(){
			var grid = Ext.create('Ext.com.bkfm.datagrid', {
				title: "菜单角色",
				id: "menuRoleGrid",
				objPath : "ROOT/XTGLPT/JCSJGL/CDXX/BLK_MENU_ROLES",
				border: true,
				listeners:{
					"itemclick": function(grid,record,item,index,e,eOpts ){
						Ext.getCmp("menuRoleBtnGrid").getSelectionModel().deselectAll();
						var menu_roles_rwid = record.getId();
						//查询菜单所属用户角色对应的按钮权限
						BkfmDBUtils.Query("SELECT MENU_ROLES_RWID,BTN_PERMIS_RWID FROM BLK_ROLE_BTN_PERMIS WHERE MENU_ROLES_RWID='"+menu_roles_rwid+"'",function(result){
							if(result.status == 'OK'){
								var records = result.list;
								var sel_records = [];
								for(i in records){
									var btn_permis_rwid = records[i].BTN_PERMIS_RWID;
									Ext.getCmp("menuRoleBtnGrid").selectRecordById(btn_permis_rwid)
								}
							}
						});
					}
				},
				afterFormShow: function(gridPanel,formTabPanel){
					var treeNode = Ext.getCmp("menuTree").getSelectNode();
					var form = formTabPanel.items.get(0);
					form.setFieldValue(form.findById("MENU_RWID"),{
						VALUE: treeNode.get("id"),
						DISPLAYVALUE: treeNode.get("text")
					});
				}
			});
			return grid;
		},
		/**
		 * 选择功能图标
		 */
		createIconPanel: function(){
			var me = this;
			
			var data = [];
			for(i=1;i<=53;i++){
				data.push({
					"index": (i-1),
					"icon_32": "icon_"+i+"_32",
					"icon_32_img": CONTEXT.contextPath + '/assets/plug-in/css/images/desktop_icon/icon_'+i+'_32.png',
					"icon_48": "icon_"+i+"_48",
					"icon_48_img": CONTEXT.contextPath + '/assets/plug-in/css/images/desktop_icon/icon_'+i+'_48.png'
				});
			}

		    Ext.define('ImageModel', {
		        extend: 'Ext.data.Model',
		        fields: [
		            {name: 'index'},
		            {name: 'icon_32'},
		            {name: "icon_32_img"},
		            {name: "icon_48"},
		            {name:"icon_48_img"}
		        ]
		    });

		    var store = Ext.create('Ext.data.JsonStore', {
		        model: 'ImageModel',
		        sortInfo: {
		            field    : 'name',
		            direction: 'ASC'
		        },
		        data: data
		    });
		    var dataview = Ext.create('Ext.view.View', {
		        deferInitialRefresh: false,
		        store: store,
		        tpl  : Ext.create('Ext.XTemplate',
		            '<tpl for=".">',
		                '<div class="data" style="background-image:()">',
		                    (!Ext.isIE6? '<img width="64" height="64" src="{[values.icon_48_img]}" />' :
		                     '<div style="width:74px;height:74px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'{[values.icon_48_img]}\',sizingMethod=\'scale\')"></div>'),
		                    '<strong>ICON_{index}</strong>',
		                '</div>',
		            '</tpl>'
		        ),
		        plugins : [
		            Ext.create('Ext.ux.DataView.Animated', {
		                duration  : 550,
		                idProperty: 'index'
		            })
		        ],
		        id: 'phones',
		        itemSelector: 'div.data',
		        overItemCls : 'phone-hover',
		        multiSelect : true,
		        autoScroll  : true,
		        listeners:{
		        	"itemclick": function(view,record,el,eOpts ){
		        		var field = Ext.getCmp("menuform").findById("ICON_URL");
		        		field.setValue(record.get("icon_48"));
		        		Ext.getCmp("iconWin").close();
		        	}
		        }
		    });
		    

		    
		   var iconWin = Ext.create('Ext.com.bkfm.window', {
				title : '选择图标',
				autoScroll : true,
				modal : true,
				id: "iconWin",
				height : Utils.getHeight()*0.9,
				width : Utils.getWidth()*0.8,
				items:[dataview],
				tbar:[{
					text: "确定",
					iconCls: 'ok',
					handler: function(){
						
					}
				},{
					text: "关闭",
					iconCls: "close",
					handler: function(){
						iconWin.close();
					}
				}]
			}).show();
		},
		/**
		 * 菜单页面对应的功能按钮权限
		 */
		createMenuRoleBtnPersim: function(){
			var grid = Ext.create('Ext.com.bkfm.datagrid', {
				title: "菜单功能权限",
				id: "menuRoleBtnGrid",
				objPath : "ROOT/XTGLPT/JCSJGL/QXGL/BLK_V_BTN_PERMIS",
				border: true,
				orderby : ' ORDER BY BTN_LEVEL ASC,ORDER_BY ASC',
				loadAuto: false,
				showstandardBtn: false,
				tbar:[{
					text: '保存按钮权限',
					iconCls: 'save',
					handler: function(){
						var treeNode = Ext.getCmp("menuTree").getSelectNode();
						if(treeNode.raw.menu_type != "1"){
							AjaxUtils.showError("选择的非页面菜单不可设置功能权限");
							return ;
						}
						var menuRoleGrid = Ext.getCmp("menuRoleGrid");
						if(menuRoleGrid.getSelectedRecords().length == 0){
							AjaxUtils.showError("请选择需要需要维护的角色");
							return ;
						}
						//获取菜单用户角色
						var menu_role_record = menuRoleGrid.getSelectedRecords()[0];
						var menu_roles_rwid = menu_role_record.getId();
						//获取选中的按钮权限记录
						var btn_records = Ext.getCmp("menuRoleBtnGrid").getSelectedRecords();
						var param = [];
						for(i in btn_records){
							var btn_r = btn_records[i];
							param.push({
								"obj_path": "ROOT/XTGLPT/JCSJGL/QXGL/BLK_ROLE_BTN_PERMIS",
								"record_state": Constants.RECORD_NEW,
								"rwid": Utils.getRwid(),
								"record_data":Ext.JSON.encode({
									"MENU_ROLES_RWID": menu_roles_rwid,
									"BTN_PERMIS_RWID": btn_r.getId()
								})
							});
						}
						//先删除
						BkfmDBUtils.Execute("DELETE FROM BLK_ROLE_BTN_PERMIS WHERE MENU_ROLES_RWID='"+menu_roles_rwid+"'",function(result){
							if(result.status=="OK"){
								AjaxUtils.CallService({
									url: CONTEXT.contextPath+"/bkfm/metadata/v1/savemodelmetadata",
									dataType: "json",
									params: param,
									call: function(data){
										if(data.status == "OK"){
											AjaxUtils.showInfo('操作成功');
										}else{
											AjaxUtils.showError('操作失败');
										}
									}
								});
							}
						});
						
					}
				},{
					text: '新建',
					iconCls: 'add',
					handler: function(){
						var treeNode = Ext.getCmp("menuTree").getSelectNode();
						if(treeNode.raw.menu_type != "1"){
							AjaxUtils.showError("选择的非页面菜单不可设置功能权限");
							return ;
						}
						var menuRoleGrid = Ext.getCmp("menuRoleGrid");
						if(menuRoleGrid.getSelectedRecords().length == 0){
							AjaxUtils.showError("请选择需要需要维护的角色");
							return ;
						}
						
						var form = Ext.create('Ext.com.bkfm.form', {
							showGroup : false,
							border : false,
							frameborder : false,
							objPath : "ROOT/XTGLPT/JCSJGL/QXGL/BLK_CUSTOM_BTN_PERMIS",
							listeners:{
								afterrender: function(form,eopts){
									form.setFieldValue(form.findById("MENU_RWID"),{
										VALUE: treeNode.get("id"),
										DISPLAYVALUE: treeNode.get("text")
									});
								}
							}
						});
						var win = Ext.create('Ext.com.bkfm.window', {
							title : "新建",
							autoScroll : true,
							modal : true,
							height : Utils.getHeight()*0.8,
							width : Utils.getWidth()*0.7,
							items:[form],
							tbar:[{
								text: '保存',
								iconCls: 'save',
								handler: function(){
									form.save(function(){
										Ext.getCmp("menuRoleBtnGrid").reload();
									});
								}
							},{
								text: '关闭',
								iconCls: 'close',
								handler: function(){
									win.close();
								}
							}]
						}).show();
					}
				},{
					text: '删除',
					iconCls: 'delete',
					handler: function(){
						var records = grid.getSelectedRecords();
						if(records.length == 0){
							return;
						}
						var del_param = new Array();
						for(i in records){
							var r = records[i];
							if(r.get("BTN_LEVEL") == "0"){
								AjaxUtils.showError("系统按钮不允许删除");
								return;
							}
							del_param.push({
								"obj_path": "ROOT/XTGLPT/JCSJGL/QXGL/BLK_CUSTOM_BTN_PERMIS",
								"rwid": r.getId()
							});
						}
						AjaxUtils.showConfirm(function(){
							AjaxUtils.CallService({
								url: CONTEXT.contextPath+"/bkfm/metadata/v1/delmodelmetadata",
								dataType: "json",
								params: del_param,
								call: function(result){
									grid.reload();
								}
							});			
						},"确定需要删除选中的记录？删除后将不可恢复!");
					}
				}]
			});
			return grid;
		}
}